package com.rj.bd.kj.fdc.rsa;

import com.rj.bd.kj.fdc.MyAbstractClassFDC;

import java.security.*;
import javax.crypto.Cipher;
import java.util.Base64;

/**
 * @desc: RSA加密解密工具类
 * @author: 博闻
 *
 */

public class RSAImplementation extends MyAbstractClassFDC {
    // 生成指定位数和格式的密钥对的方法无需修改

    @Override
    public KeyPair generateKeyPair(int keySize, String keyFormat) throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(keySize);
        return keyPairGenerator.generateKeyPair();
    }

    @Override
    public byte[] encrypt(byte[] data, String publicKeyStr, String charset) throws Exception {
        PublicKey publicKey = RSAUtils.getPublicKey(Base64.getDecoder().decode(publicKeyStr));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(data);
        // 直接进行Base64编码，假设都使用UTF - 8编码
        return Base64.getEncoder().encode(encryptedBytes);
    }

    @Override
    public byte[] decrypt(byte[] encryptedData, String privateKeyStr, String charset) throws Exception {
        PrivateKey privateKey = RSAUtils.getPrivateKey(Base64.getDecoder().decode(privateKeyStr));
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        if ("UTF-8".equals(charset)) {
            encryptedData = Base64.getDecoder().decode(encryptedData);
        }
        return cipher.doFinal(encryptedData);
    }

    @Override
    public byte[] encrypt(byte[] originalBytes, PublicKey publicKey, String s) {
        return new byte[0];
    }

    @Override
    public byte[] decrypt(byte[] eData, PrivateKey privateKey, String s) {
        return new byte[0];
    }
}